/**
 * 
 */
package ch.baeni.jee.util;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import ch.baeni.jee.model.User;
import ch.baeni.jee.util.SLL_Globals.UserRole;
import ch.baeni.jee.web.LoginBean;

/**
 * @author Benjamin
 *
 */
public class AuthorisationListener implements PhaseListener {

	private static final long serialVersionUID = 1L;

	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		String currentPage = facesContext.getViewRoot().getViewId();
		boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
		boolean isRegisterPage = (currentPage.lastIndexOf("registration.xhtml") > -1);
		boolean isAdminPage = (currentPage.lastIndexOf(UserRole.admin.name()) > -1);
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
		
		if (session == null){
			NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
			nh.handleNavigation(facesContext, null, "login");
		}
		else {
			User currentUser = null;
			LoginBean loginBean = (LoginBean) session.getAttribute("loginBean");
			if (loginBean != null) {
				currentUser = loginBean.getCurrentUser();
			}
			if (!isLoginPage && !isRegisterPage && (currentUser == null)) {
				NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
				nh.handleNavigation(facesContext, null, "login");
			} else if (isAdminPage && !currentUser.isAdmin()) {
				NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
				nh.handleNavigation(facesContext, null, "accessDenied");
			}
		}
	}

	public void beforePhase(PhaseEvent arg0) {
				
	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
